import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { connect } from 'dva';
import PageLoading from '@/components/PageLoading';
import { FormattedMessage } from 'umi-plugin-react/locale';
import { Row, Col, Card, Icon, Tooltip, Form, Input, Button, Switch, Radio, message, BackTop, Spin, Upload, } from 'antd';
import Editor from '@/utils/Editor';
import styles from './index.less';
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_m18hmgbwet.js', // 在 iconfont.cn 上生成
});
import ljx from '../../../assets/icons/垃圾箱.png';

class robotSetup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      content: '',
      commonProblemList: [{ name: '', item: '' }],
      pdxs: true,
      valueA: '1',
      Chat: null,
      BaiKe: null,
      CommunityQA: null,
      Chatpd: false,
      BaiKepd: false,
      CommunityQApd: false,
      timedaan: '',
      list: {},
      hyy: '',
      enableChat: false,
      enableBaike: false,
      enableCommunity: false,
      login: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    this.fetchc()
  }

  switchA = a => {
    // 闲聊知识库
    this.setState({ enableChat: a });
  };

  //  --------------------热门问题-----------------
  handleAdditem = () => {
    if (this.state.commonProblemList.length > 9) {
      message.error('常见问题最多可以添加10个');
    } else {
      this.setState(
        a => ({
          commonProblemList: [...a.commonProblemList, { name: '' }],
        }),
        () => {
          let a = this.state.commonProblemList;

          for (var i = 0; i < a.length - 1; i++) {
            a[i].name = 'tcx';
          }

          this.setState({ commonProblemList: a }, () => {
            const { input } = this.inputRef; // 如果是textArea的话，const { textAreaRef } = this.inputRef;
            input.focus();
            input.setSelectionRange(0, input.value.length);
          });
          // }
        }
      );
    }
  };

  handleSubmitAs = e => {
    let a = this.state.commonProblemList;
    a.splice(e, 1);
    this.setState({ commonProblemList: a });
  };

  // 上移
  handleSubmitAyd = index => {
    let arr = this.state.commonProblemList;
    this.upData(arr, index);
  };

  upData = (arr, index) => {
    var swapItems = function (arr, index1, index2) {
      arr[index1] = arr.splice(index2, 1, arr[index1])[0];
      return arr;
    };
    var newArr = [];
    if (arr.length > 1 && index !== 0) {
      newArr = swapItems(arr, index, index - 1);
    };
    if (newArr.length === 0) {
      message.info(`再上移就没了`);
    } else {
      this.setState({ commonProblemList: newArr });
    }
  };

  // 上移结束

  zjrmwt = (e, b) => {
    let a = this.state.commonProblemList;
    a[b].item = e.target.value;
    this.setState({ commonProblemList: a });
  };

  onChangeValue = e => {
    this.setState({
      valueA: e.target.value,
    });
  };

  checkName = (rule, value, callback) => {
    if (value.length > 10) {
      callback('昵称最多为10个字符');
    } else {
      callback();
    }
  };

  // eslint-disable-next-line react/sort-comp
  render() {
    const { getFieldDecorator } = this.props.form;
    const FormItemLayont = {
      labelCol: {
        sm: 24,
        md: 3,
      },
      wrapperCol: {
        sm: 24,
        md: 16,
      },
    };
    const displayp = {
      display: 'none',
    };

    return (
      <div>
        <Spin spinning={this.state.login}>
          <Card bordered={false}>
            <Form layout="horizontal" {...FormItemLayont}>
              <FormItem label="机器人名称" >
                {getFieldDecorator('robotName', {
                  initialValue: this.state.list.name,
                  rules: [
                    {
                      required: true,
                      message: '请填写机器人名称',
                    },
                    {
                      validator: this.checkName,
                    },
                  ],
                })(<Input maxLength={200} />)}
              </FormItem>
              <FormItem label="昵称" >
                {getFieldDecorator('userName', {
                  initialValue: this.state.list.nick,
                  rules: [
                    {
                      required: true,
                      message: '请填写机器人昵称',
                    },
                    {
                      validator: this.checkName,
                    },
                  ],
                })(<Input maxLength={200} />)}
              </FormItem>
              <FormItem label="性别">
                {getFieldDecorator('gender', {
                  initialValue: this.state.list.gender,
                  rules: [
                    {
                      required: true,
                      message: '请填写机器人性别',
                    },
                  ],
                })(<Input maxLength={20} />)}
              </FormItem>
              <FormItem label="介绍">
                {getFieldDecorator('introduce', {
                  initialValue: this.state.list.description,
                  rules: [
                    {
                      required: true,
                      message: '请填写机器人介绍',
                    },
                  ],
                })(<Input maxLength={200} />)}
              </FormItem>
              <FormItem className="editor" label="欢迎语">
                {getFieldDecorator('hyy11', {
                  initialValue: this.state.valueA,
                  rules: [{ required: true }],
                })(
                  <RadioGroup onChange={this.onChangeValue}>
                    <Radio value="1">用以下内容作为欢迎语</Radio>
                    <Radio value="2">用以下问题的答案作为欢迎语</Radio>
                  </RadioGroup>
                )}

                <div style={this.state.valueA !== '1' ? displayp : null}>
                  <Editor
                    content={this.state.content}
                    name="content"
                    id="content"
                    height="200"
                    width="500"
                    ref={r => (this.ueditor = r)}
                  />
                </div>
                {getFieldDecorator('hyy', {
                  initialValue: this.state.hyy,
                })(
                  <Input
                    onChange={this.timedaan}
                    style={this.state.valueA !== '2' ? displayp : null}
                    placeholder=""
                    maxLength={200}
                  />
                )}
              </FormItem>
              <FormItem label="常见问题">
                <div>
                  {this.state.commonProblemList.map((item, index) => {
                    return (
                      <div className={styles.flexMap} key={index}>
                        <Input
                          ref={this.state.commonProblemList.length - 1 === index ? input => (this.inputRef = input) : 'a'}
                          onPressEnter={this.handleAdditem}
                          value={item.item}
                          onChange={e => this.zjrmwt(e, index)}
                          placeholder=""
                          maxLength={200}
                        />
                        {item.name === '' ? null : (
                          <span className={styles.qnmb}>
                            <Icon
                              onClick={() => this.handleSubmitAyd(index)}
                              type="arrow-up"
                              style={{ marginLeft: 5, width: 14, padding: '8px 0px 12px 0px' }}
                            />
                            <img
                              src={ljx}
                              style={{
                                marginLeft: 5,
                                width: 14,
                                padding: '8px 0px 12px 0px',
                                cursor: 'pointer',
                              }}
                              onClick={() => this.handleSubmitAs(index)}
                            />
                          </span>
                        )}
                      </div>
                    );
                  })}
                  <Button onClick={this.handleAdditem}>新增常见问题</Button>
                </div>
              </FormItem>
              <FormItem label="未知问题回答">
                {getFieldDecorator('unknownAnswer', {
                  initialValue: this.state.list.unknown,
                  rules: [
                    {
                      required: true,
                      message: '请填写机器人未知问题回答',
                    },
                  ],
                })(<Input placeholder="" maxLength={200} />)}
              </FormItem>
              <FormItem label="闲聊知识库">
                <Switch
                  onChange={this.switchA}
                  checkedChildren="开"
                  unCheckedChildren="关"
                  checked={this.state.enableChat}
                />
              </FormItem>
            </Form>
          </Card>
          <Card bordered={false}>
            <div style={{ height: 50 }}></div>
            <div className="backtop">
              <BackTop visibilityHeight={-100}>
                <Button type="primary" onClick={this.saveFrom} style={{ marginRight: 10 }}>保存</Button>
              </BackTop>
            </div>
          </Card>
        </Spin>
      </div>
    );
  }

  czjqr = () => {
    const { dispatch } = this.props;
    this.reqRef = requestAnimationFrame(() => {
      dispatch({
        type: 'robotSetup/fetch',
        payload: {},
        callback: res => {
          if (res.status == 0) {
            message.success(`重置成功`);
          }
        },
      });
    });
  };

  timedaan = e => {
    this.setState({ timedaan: e.target.value });
  };

  saveFrom = () => {
    let a = this.state.commonProblemList;
    let b = [];
    a.map(item => {
      b.push(item.item);
    });

    const { timedaan, headUrl } = this.state;
    const { robotId } = this.props;
    // if(timedaan === ''){
    //   message['error'](`用以下问题的答案作为欢迎语`)
    // }

    const welcomeInfo = {};
    welcomeInfo.welcomeType = Number(this.state.valueA);
    if (this.state.valueA == '1') {
      this.setState({ timedaan: '' });
      if (this.ueditor.getUeditorContent()) {
        welcomeInfo.content = this.ueditor.getUeditorContent();
      } else {
        message.error('欢迎语不能为空');
        return;
      }
    } else {
      this.setState({ content: '' });
      if (this.state.timedaan) {
        welcomeInfo.content = timedaan;
      } else {
        message.error('欢迎语不能为空');
        return;
      }
    };

    let userInfo = this.props.form.getFieldsValue(); // 获取数据
    this.props.form.validateFields((err, values) => {
      // 校验方法
      if (!err) {
        const { dispatch, currentUser } = this.props;
        this.reqRef = requestAnimationFrame(() => {
          dispatch({
            type: 'robotSetup/fetchb',
            payload: {
              name: userInfo.robotName,
              nick: userInfo.userName,
              gender: userInfo.gender,
              description: userInfo.introduce,
              unknown: userInfo.unknownAnswer,
              chatDisabled: this.state.enableChat ? 0 : 1,
              questions: b,
              welcomeType: welcomeInfo.welcomeType,
              welcome: welcomeInfo.content,
              headPath: headUrl,
              id: robotId
            },
            callback: res => {
              message.success(`${res.message}`);
              this.fetchc();
            },
          });
        });
      }
    });
  };

  fetchc = () => {
    this.setState({ login: true }, () => {
      const { dispatch, currentUser, robotId } = this.props;
      this.reqRef = requestAnimationFrame(() => {
        dispatch({
          type: 'robotSetup/fetchc',
          payload: { id: robotId },
          callback: res => {
            console.log(res);
            if (res.questions[0] && res.questions[0] !== '') {
              let b = [];
              let a = res.questions;
              a.map((item, index) => {
                let c = { name: 'tcx', item: item };
                b.push(c);
              });
              this.setState({ commonProblemList: b });
            };
            if (res.welcomeType === 1) {
              this.setState({ content: res.welcome, });
            } else {
              this.setState({ hyy: res.welcome, timedaan: res.welcome, });
            };
            this.setState({
              list: res,
              valueA: res.welcomeType ? String(res.welcomeType) : '1',
              enableChat: res.chatDisabled === 1 ? false : true,
              login: false,
            });
          },
        });
      });
    });
  };
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(robotSetup));
